package com.example.demo.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class PasswordTool {
    public static String encrypt(String password) {
        //1产生盐值
        String salt = UUID.randomUUID().toString().replace("-", "");
        //2使用(盐值+明文密码)得到加密的密码
        String finalPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        //3将盐值和加密的密码共同返回(合并盐值和加密)
        return salt + "$" + finalPassword;
    }

    public static String encrypt(String password, String salt) {
        String finalPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        return salt + "$" + finalPassword;
    }

    public static boolean decrypt(String password, String dbPassword) {
        boolean result = false;
        if (StringUtils.hasLength(password) && StringUtils.hasLength(dbPassword) &&
                dbPassword.length() == 65 && dbPassword.contains("$")) {
            //1得到盐值
            String[] passwordArr = dbPassword.split("\\$");
            //1.1盐值
            String salt = passwordArr[0];
            //1.2得到正确的加盐加密密码
            String finalPassword = passwordArr[1];
            //2生成验证密码的加盐加密密码
            String checkPassword = encrypt(password, salt);
            if (dbPassword.equals(checkPassword)) {
                result = true;
            }
        }
        return result;
    }
}